<?php


namespace catchAdmin\ca\controller;


use app\common\lib\Redis;
use app\common\model\PatientInfo;
use catchAdmin\ca\validate\LoginValidate;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;
use catcher\library\client\Response;
use thans\jwt\facade\JWTAuth;
use thans\jwt\provider\JWT;
use think\Config;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class UserCenter extends CatchController
{
    protected $business = null;

    public function __construct()
    {
        $this->business = new \app\common\business\UserCenter();
    }

    public function getToken(Request $request): \think\response\Json
    {
        $idCard = $request->param('id_card', '', 'string');
        $name = $request->param('patient_name', '', 'string');
        if (trim(empty($idCard)) || trim(empty($name))) {
            throw new ValidateFailedException("请检查必填参数");
        }
        $patientInfo = (new PatientInfo())->getPatientInfoByCard($idCard);
        if (empty($patientInfo)) {
            throw new FailedException("无效的用户");
        }
        if (trim($patientInfo["name"]) !== trim($name)) {
            throw new FailedException("无效的用户");
        }

        $ticket = (new \app\common\business\UserCenter())->generateTicket(["patient_code" => $idCard]);
        return CatchResponse::success(['ticket' => $ticket]);
    }


    public function certificationCenter(Request $request): \think\response\Json
    {
        try {

            $token = '';
            $postData = $request->param();
            validate(LoginValidate::class)->scene("login")->check($postData);
            $userCode = "";
            if ($postData["platform"] === 1) {
                $userInfo = $this->business->getDoctorInfo($postData);
                $userCode = $userInfo["doctor_code"];
            } else {
                $userInfo = $this->business->getUserInfo($postData);
                $userCode = $userInfo["patientId"];

            }
            $token = JWTAuth::builder(["admin_id" => $userInfo["id"], "platform" => $postData["platform"]]);
            $userKey = hash("sha256", $userInfo["id"] . "_" . $_SERVER["REMOTE_ADDR"] . '_' . $_SERVER["HTTP_USER_AGENT"]);
            Redis::getInstance()->redis->setex($userKey, 3600, $token);
            Redis::getInstance()->redis->setex("jwt:user:" . $userInfo["id"], 86400, $token);
            return CatchResponse::success(["token" => $token, "user_id" => $userInfo["id"], "userCode" => $userCode]);
        } catch (ValidateException $validateException) {
            throw new ValidateFailedException($validateException->getMessage());
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }
}